<script setup>
import { ref, onMounted } from 'vue'
import axios from '../plugins/axios'
import Pagination from '../components/Pagination.vue'
import { ElImageViewer, ElPagination, ElMessageBox, ElMessage } from 'element-plus'
import PostEditor from '../components/PostEditor.vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 帖子列表数据
const posts = ref([])

// 搜索条件
const searchForm = ref({
  labelId: 0,
  keyword: '',
  filter: 'latest',
  page: 1,
  rows: 10
})

// 获取帖子列表数据
const fetchPosts = async () => {
  try {
    const response = await axios.post('/post/queryByCondition', searchForm.value)
    
    if (response.data.code === 1) {
      posts.value = response.data.data
      pagination.value.total = response.data.total || 0
      console.log('获取帖子列表成功:', posts.value)
    } else {
      console.error('获取帖子列表失败:', response.data.msg)
      posts.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取帖子列表请求失败:', error)
    posts.value = []
    pagination.value.total = 0
  }
}

// 帖子分类
const labels = ref([
])

// 获取标签数据
const fetchLabels = async () => {
  try {
    const response = await axios.get('/label/queryAll')
    if (response.data.code === 1) {
      // 将获取到的数据添加到labels中
      labels.value = [
        ...response.data.data
      ]
    } else {
      console.error('获取标签列表失败:', response.data.msg)
    }
  } catch (error) {
    console.error('获取标签列表请求失败:', error)
  }
}

// 当前选中的标签
const currentlabel = ref(0)

// 分页信息
const pagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 快速筛选选项
const filterOptions = [
  { value: 'latest', label: '最新' },
  { value: 'hot', label: '热门' }
]

// 处理标签切换
const handlelabelChange = (labelId) => {
  // 更新当前选中的标签
  currentlabel.value = labelId
  
  // 更新搜索条件中的标签ID
  searchForm.value.labelId = labelId
  
  // 重置页码
  searchForm.value.page = 1
  
  // 重新获取帖子列表
  fetchPosts()
}

// 处理筛选切换
const handleFilterChange = (filter) => {
  // 更新筛选条件
  searchForm.value.filter = filter
  
  // 重置页码
  searchForm.value.page = 1
  
  // 重新获取帖子列表
  fetchPosts()
}

// 处理搜索
const handleSearch = () => {
  fetchPosts()
}

// 处理重置
const handleReset = () => {
  searchForm.value = {
    labelId: 0,
    keyword: '',
    filter: 'latest',
    page: 1,
    rows: 10
  }
  currentlabel.value = 0
  handleSearch()
}

// 处理页码变化
const handlePageChange = (newPage) => {
  searchForm.value.page = newPage
  fetchPosts()
}

// 处理每页显示数量变化
const handlePageSizeChange = (newSize) => {
  searchForm.value.rows = newSize
  searchForm.value.page = 1  // 重置到第一页
  fetchPosts()
}

// 发帖对话框控制
const editorVisible = ref(false)
const editData = ref(null)

// 处理发帖
const handleCreatePost = () => {
  editData.value = null  // 清空编辑数据
  editorVisible.value = true  // 显示对话框
}

// 获取当前登录用户信息
const currentUser = JSON.parse(localStorage.getItem('user') || '{}')

// 处理删除帖子
const handleDeletePost = async (postId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/post/${postId}`)
    if (response.data.code === 1) {
      ElMessage.success('删除成功')
      fetchPosts() // 刷新帖子列表
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除帖子失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理编辑帖子
const handleEditPost = (post) => {
  editData.value = post
  editorVisible.value = true
}

// 处理提交完成
const handleSubmitComplete = () => {
  fetchPosts()  // 刷新帖子列表
}

// 图片预览相关
const showImageViewer = ref(false)
const currentImage = ref('')

// 处理图片点击
const handleImageClick = (src) => {
  currentImage.value = src
  showImageViewer.value = true
}

// 处理视频点击
const handleVideoClick = (event) => {
  const video = event.target
  if (video.paused) {
    video.play()
  } else {
    video.pause()
  }
}

const router = useRouter()

// 处理帖子点击
const handlePostClick = (postId) => {
  router.push(`/reply/${postId}`)
}

onMounted(() => {
  fetchLabels()  // 获取标签数据
  fetchPosts()   // 获取帖子列表数据
})
const formatTime = (time) => {
  if (!time) return ''
  return time.split('.')[0]  // 用分割的方式去掉 .0
}
const userId = ref(localStorage.getItem('userId') ? Number(localStorage.getItem('userId')) : null)
const isAdmin = localStorage.getItem('isAdmin') === '1'
</script>

<template>
  <div class="forum-container">
    <div class="page-header">
      <h1>贴吧</h1>
      <button class="create-post-btn" @click="handleCreatePost">发布帖子</button>
    </div>

    <!-- 标签导航 -->
    <div class="label-nav">
      <button 
        class="label-btn" 
        :class="{ active: currentlabel === 0 }"
        @click="handlelabelChange(0)">全部</button>
      <button
        v-for="label in labels"
        :key="label.id"
        class="label-btn"
        :class="{ active: currentlabel === label.id }"
        @click="handlelabelChange(label.id)"
      >
        {{ label.labelName }}
      </button>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <div class="search-input-group">
        <input 
          type="text" 
          v-model="searchForm.keyword" 
          placeholder="搜索帖子"
          class="search-input"
        >
        <button class="search-btn" @click="handleSearch">搜索</button>
      </div>
      <div class="filter-tags">
        <button
          v-for="option in filterOptions"
          :key="option.value"
          class="filter-tag"
          :class="{ active: searchForm.filter === option.value }"
          @click="handleFilterChange(option.value)"
        >
          {{ option.label }}
        </button>
      </div>
    </div>

    <!-- 帖子列表 -->
    <div class="posts-list">
      <div v-for="post in posts" :key="post.id" class="post-item">
        <div class="post-user-info">
          <img 
            class="user-avatar" 
            :src="post.isAnonymous ? '/default-avatar.png' : (post.user.head || '/default-avatar.png')" 
            :alt="post.isAnonymous ? '匿名用户' : (post.user.realName + '的头像')"
          />
          <div class="user-name">{{ post.isAnonymous ? '匿名用户' : post.user.realname }}</div>
          <div class="post-role"></div>
        </div>
        <div class="post-content">
          <div class="post-header">
            <h3 class="post-title" @click="handlePostClick(post.id)">{{ post.title }}</h3>
            <span class="post-label">{{ post.label.labelName }}</span>
          </div>
          <div 
            class="post-text" 
            v-html="post.content"
            @click="e => {
              if (e.target.tagName === 'IMG') {
                handleImageClick(e.target.src)
              }
              if (e.target.tagName === 'VIDEO') {
                handleVideoClick(e)
              }
            }"
          ></div>
          <div class="post-meta-time">
            <div class="post-info">
              <span class="time">发布时间：{{ formatTime(post.publishTime) }}</span>
              <span class="last-reply">最后回复：{{ formatTime(post.lastReplyTime) }}</span>
            </div>
          </div>  
          <div class="post-meta">
            <div class="post-left">
              <span class="views">浏览 {{ post.viewCount }}</span>
              <span class="replies">回复 {{ post.replyCount }}</span>
            </div>
            <div class="post-right" v-if="post.userId === userId">
              <button class="action-btn edit" @click="handleEditPost(post)"  v-if="(isAdmin || userId === post.userId)">编辑</button>
              <!-- <button class="action-btn delete" @click="handleDeletePost(post.id)">删除</button> -->
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="[currentImage]"
      :initial-index="0"
      @close="showImageViewer = false"
    />

    <!-- 发帖/编辑对话框 -->
    <PostEditor
      v-model:visible="editorVisible"
      :edit-data="editData"
      :is-edit="!!editData"
      :label-options="labels"
      @on-submit="handleSubmitComplete"
    />
  </div>
</template>

<style scoped>
.forum-container {
  padding: 2rem;
  margin-top: 60px;
}
.post-meta-time {
  border-top: 1px solid #E4E7EB;
  padding-top: 1rem;
}

.post-meta-time .post-info {
  display: flex;
  gap: 1rem;
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 1.8rem;
}

.action-btn {
  padding: 0.25rem 0.75rem;
  border: 1px solid #DFE1E6;
  background-color: white;
  border-radius: 3px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.action-btn.assign {
  background-color: #fff;
  color: #409EFF;
  border: 1px solid #409EFF;
}

.action-btn.assign:hover {
  background-color: #ecf5ff;
  color: #409EFF;
  border-color: #409EFF;
}

.action-btn.edit {
  color: #67C23A;
  border: 1px solid #67C23A;
}

.action-btn.edit:hover {
  background-color: #f0f9eb;
  border-color: #67C23A;
  color: #67C23A;
}

.action-btn.delete {
  color: #F56C6C;
  border: 1px solid #F56C6C;
}

.action-btn.delete:hover {
  background-color: #fef0f0;
  border-color: #F56C6C;
  color: #F56C6C;
}

.create-post-btn {
  padding: 0.5rem 1rem;
  background-color: #0052cc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.create-post-btn:hover {
  background-color: #0747a6;
}

.label-nav {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
  overflow-x: auto;
  padding-bottom: 0.5rem;
}

.label-btn {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.2s;
}

.label-btn.active {
  background-color: #0052cc;
  color: white;
  border-color: #0052cc;
}

.label-btn:hover:not(.active) {
  border-color: #0052cc;
  color: #0052cc;
}

.search-form {
  background-color: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.search-input-group {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.search-input {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.search-btn {
  padding: 0.75rem 2rem;
  background-color: #0052cc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.search-btn:hover {
  background-color: #0747a6;
}

.filter-tags {
  display: flex;
  gap: 1rem;
}

.filter-tag {
  padding: 0.5rem 1.5rem;
  border: 1px solid #ddd;
  border-radius: 20px;
  background-color: white;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}

.filter-tag:hover,
.filter-tag.active {
  background-color: #0052cc;
  color: white;
  border-color: #0052cc;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.post-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: #fff;
}

.post-user-info {
  width: 100px;
  text-align: center;
  margin-right: 20px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-bottom: 8px;
}

.user-name {
  font-size: 14px;
  color: #666;
}

.post-role {
  color: #666;
  font-size: 0.8rem;
}

.post-content {
  flex: 1;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.post-title {
  margin: 0;
  font-size: 1.2rem;
  color: #172B4D;
  cursor: pointer;
  transition: color 0.2s;
}

.post-title:hover {
  color: #0052cc;
}

.post-label {
  padding: 0.25rem 0.75rem;
  background-color: #EAE6FF;
  color: #403294;
  border-radius: 3px;
  font-size: 0.8rem;
}

.post-text {
  color: #42526E;
  margin-bottom: 1rem;
  line-height: 1.5;
}

.post-text :deep(img),
.post-text :deep(video) {
  height: 160px;
  width: auto;
  object-fit: contain;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.post-text :deep(img):hover,
.post-text :deep(video):hover {
  transform: scale(1.05);
}

/* 确保图片和视频不会超出容器 */
.post-text {
  max-width: 100%;
  overflow: hidden;
}

/* 全屏时恢复原始尺寸 */
.post-text :deep(img):fullscreen,
.post-text :deep(video):fullscreen {
  height: auto;
  width: auto;
  max-height: 100vh;
}

.post-text :deep(p) {
  margin: 0.5em 0;
}

.post-text :deep(a) {
  color: #0052cc;
  text-decoration: none;
}

.post-text :deep(a):hover {
  text-decoration: underline;
}

/* 富文本内容的其他样式 */
.post-text :deep(h1),
.post-text :deep(h2),
.post-text :deep(h3),
.post-text :deep(h4),
.post-text :deep(h5),
.post-text :deep(h6) {
  margin: 1em 0 0.5em;
  line-height: 1.2;
  color: #172B4D;
}

.post-text :deep(ul),
.post-text :deep(ol) {
  padding-left: 2em;
  margin: 0.5em 0;
}

.post-text :deep(blockquote) {
  margin: 1em 0;
  padding: 0.5em 1em;
  border-left: 4px solid #ddd;
  background: #f5f5f5;
  color: #666;
}

.post-text :deep(code) {
  background: #f5f5f5;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: monospace;
}

.post-text :deep(pre) {
  background: #f5f5f5;
  padding: 1em;
  border-radius: 4px;
  overflow-x: auto;
}

.post-media {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.media-section {
  flex: 1;
}

.section-title {
  font-weight: bold;
  color: #172B4D;
  margin-bottom: 0.5rem;
}

.media-placeholder {
  background-color: #F4F5F7;
  padding: 2rem;
  border-radius: 4px;
  text-align: center;
  color: #666;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.post-left {
  display: flex;
  gap: 20px;
  color: #666;
}

.post-right {
  display: flex;
  gap: 8px;
}

.post-right .el-button {
  padding: 6px;
}

.views, .replies {
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>